<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');


class Faculty extends CCMIS_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('model_facultymember');
        $this->load->model('model_facultymemberstatus');
        $this->load->model('model_facultyrankdesc');
        $this->load->model('model_facultydegreedesc');
        $this->load->model('model_ccmisdepartment');
    }

    public function index()
    {
        $this->view();
    }

    public function view()
    {
        //main page for faculty
        $this->setup_view('fmis/faculty/view');
    }

    public function profile($facultyID = -1)
    {

        $facultyID = $facultyID == -1 ? $this->session->userdata('user_id') : $facultyID;
        $details = $this->model_facultymember->getByMemberId($facultyID);

        $data = array(
            'facultyID' => $facultyID,
            'details' => $details,
        );

        $this->setup_view('fmis/faculty/profile', $data);
    }

    public function search()
    {
        if($this->input->server('REQUEST_METHOD') === 'GET')
        {
            $faculty_profiles = $this->model_facultymember->getAll();
            $profiles = array();

            foreach($faculty_profiles as $faculty_profile)
            {
                $profileStatus = $this->model_facultymemberstatus->getById($faculty_profile['Status']);
                array_push($profiles, array(
                    'profileID' => $faculty_profile['MemberID'],
                    'profileReligion' => $faculty_profile['Religion'],
                    'profileCivilStatus' => $faculty_profile['Civil_Status'],
                    'profileCitizenship' => $faculty_profile['Citizenship'],
                    'profileContactNo' => $faculty_profile['ContactNo'],
                    'profileStatus' => $profileStatus,
                    'profileGender' => $faculty_profile['Gender'],
                    'profileRank' => $this->model_facultyrankdesc->getById(1), //TODO $faculty_profile['Rank'],
                    'profileDept' => $this->model_ccmisdepartment->getDescById(1),//TODO $faculty_profile['Department'],
                    'profileSpecialty' => $faculty_profile['Specialty'],
                    'profileFirstName' => $faculty_profile['FirstName'],
                    'profileMiddleName' => $faculty_profile['MiddleName'],
                    'profileLastName' => $faculty_profile['LastName'],
                    'profileBirthDate' => $faculty_profile['Birthday'],
                    'profileAddress' => $faculty_profile['Address']
                ));
            }

            $depts = $this->model_ccmisdepartment->getAll();
            $data = array(
                'page_title' => 'Search',
                'cb_name' => 'name_filter',
                'cb_dept' => '',
                'cb_spec' => '',
                'name' => '',
                'dept' => '',
                'spec' => '',
                'archive_search' => 'unarchive',
                'departments' => $depts,
                'profiles' => $profiles
            );
            $this->setup_view('fmis/faculty/search', $data);
            return;
        }
        else
        {
            $name = $this->input->post('name_filter');
            $dept = $this->input->post('dept_filter');
            $spec = $this->input->post('spec_filter');
            $cb_name = $this->input->post('cb_name_filter');
            $cb_dept = $this->input->post('cb_dept_filter');
            $cb_spec = $this->input->post('cb_spec_filter');
            $rad_arch = $this->input->post('rad_arch_filter');

            $name = $cb_name == 'name_filter' ? $name : '';
            $dept = $cb_dept == 'dept_filter' ? $dept : '';
            $spec = $cb_spec == 'spec_filter' ? $spec : '';

            $faculty_profiles = $this->model_facultymember->search($name, $dept, $spec);
            $profiles = array();

            foreach($faculty_profiles as $faculty_profile)
            {
                $profileStatus = $this->model_facultymemberstatus->getById($faculty_profile['Status']);
                array_push($profiles, array(
                    'profileID' => $faculty_profile['MemberID'],
                    'profileReligion' => $faculty_profile['Religion'],
                    'profileCivilStatus' => $faculty_profile['Civil_Status'],
                    'profileCitizenship' => $faculty_profile['Citizenship'],
                    'profileContactNo' => $faculty_profile['ContactNo'],
                    'profileStatus' => $profileStatus,
                    'profileGender' => $faculty_profile['Gender'],
                    'profileRank' => $this->model_facultyrankdesc->getById(1), //TODO $faculty_profile['Rank'],
                    'profileDept' => $this->model_ccmisdepartment->getDescById(1),//TODO $faculty_profile['Department'],
                    'profileSpecialty' => $faculty_profile['Specialty'],
                    'profileFirstName' => $faculty_profile['FirstName'],
                    'profileMiddleName' => $faculty_profile['MiddleName'],
                    'profileLastName' => $faculty_profile['LastName'],
                    'profileBirthDate' => $faculty_profile['Birthday'],
                    'profileAddress' => $faculty_profile['Address']
                ));
            }

            $depts = $this->model_ccmisdepartment->getAll();
            $data = array(
                'page_title' => 'Search',
                'name' => $name,
                'dept' => $dept,
                'spec' => $spec,
                'cb_name' => $cb_name,
                'cb_dept' => $cb_dept,
                'cb_spec' => $cb_spec,
                'archive_search' => $rad_arch,
                'departments' => $depts,
                'profiles' => $profiles
            );

            $this->setup_view('fmis/faculty/search', $data);
            return;
            //*/

        }
    }

    public function addprofile()
    {
        if($this->input->server('REQUEST_METHOD') === 'GET')
        {
        $data = array(
            'page_title' => 'Add Profile',
            'tblStatus' => $this->model_facultymemberstatus->getAll(),
            'tblDegree' => $this->model_facultydegreedesc->getAll(),
            'tblRank' => $this->model_facultyrankdesc->getAll(),
            'tblDepartment' => $this->model_ccmisdepartment->getAll(),
            'errormsg'=> '&nbsp',

            'username'       =>'',
            'password'       =>'',
            'confirmPassword'=>'',

            'fname'          =>'',
            'mname'          =>'',
            'lname'          =>'',
            'gender'         =>'',
            'birthday'       =>'',
            'citizenship'    =>'',
            'address'        =>'',
            'civilStatus'    =>'',
            'religion'       =>'',
            'contactno'      =>'',
            'email'          =>'',
            'special'        =>'',

            'status'         =>'',
            'rank'           =>'',
            'department'     =>'',
        );
        $this->setup_view('fmis/faculty/addprofile', $data);
        }
        else
        {
            $success = true;

            $this->form_validation->set_rules('reg_username', 'Username', 'required');
            $this->form_validation->set_rules('reg_password', 'Password', 'required');
            $this->form_validation->set_rules('reg_con_password', 'Password Confirmation', 'required');

            $success = $this->form_validation->run();

            $this->form_validation->set_message('required', '%s is required!');


            $username=         $this->input->post('reg_username');
            $password=         $this->input->post('reg_password');
            $confirmPassword = $this->input->post('reg_con_password');

            $fname=            $this->input->post('edit_fname');
            $mname=            $this->input->post('edit_mname');
            $lname=            $this->input->post('edit_lname');
            $gender=           $this->input->post('edit_gender');
            $birthday=         $this->input->post('edit_birthdate');
            $citizenship=      $this->input->post('edit_citizenship');
            $address=          $this->input->post('edit_address');
            $civilstatus=      $this->input->post('edit_civilstatus');
            $religion=         $this->input->post('edit_religion');
            $contactno=        $this->input->post('edit_contactno');
            $special=          $this->input->post('edit_special');
            $email=            $this->input->post('edit_emailadd');

            $status =          $this->input->post('edit_status');
            $rank =            $this->input->post('edit_rank');
            $department =      $this->input->post('edit_department');

            $errormsg = '';


            if($password != $confirmPassword)
            {
                $errormsg = "Password and Confirmation Password mismatch";
                $success = false;
            }


            //TODO Verification if correct

            $data = array(
                'page_title' => 'Add Profile',
                'success' => $success,
                'tblStatus' => $this->model_facultymemberstatus->getAll(),
                'tblDegree' => $this->model_facultydegreedesc->getAll(),
                'tblRank' => $this->model_facultyrankdesc->getAll(),
                'tblDepartment' => $this->model_ccmisdepartment->getAll(),
                'errormsg'=> $errormsg,

                'username'       =>$username,
                'password'       =>$password,
                'confirmPassword'=>$confirmPassword,

                'fname'          =>$fname,
                'mname'          =>$mname,
                'lname'          =>$lname,
                'gender'         =>$gender,
                'birthday'       =>$birthday,
                'citizenship'    =>$citizenship,
                'address'        =>$address,
                'civilStatus'    =>$civilstatus,
                'religion'       =>$religion,
                'contactno'      =>$contactno,
                'special'        =>$special,
                'email'          =>$email,

                'status'         =>$status,
                'rank'           =>$rank,
                'department'     =>$department,



            );

            if($success == true)
            {

                $this->model_facultymember->add($username, $password, $special, $fname,$mname,$lname, $gender,
                    $civilstatus, $citizenship, $religion, $contactno, $email, $birthday ,$address, $status, $rank, $department);

                $id = $this->model_facultymember->getIdBySpecifics($fname, $mname, $lname, $birthday);

                $prevPath =  './images/fmis/members/'.$this->session->userdata('user_id').'/temp.jpg';

                $newPath =   './images/fmis/members/'.$id;
                $newFilename = '/'.$id.'.jpg';

                if (!file_exists($newPath)) {
                    mkdir($newPath, 0777, true);
                }


                rename($prevPath, $newPath.$newFilename);

                $this->profile($id);
                return;
            }
            else

            $this->setup_view('fmis/faculty/addprofile', $data);




        }

    }

    public function editstatus($id, $editStatusID)
    {
        echo 'editing status of '.$id.' to edit status: '.$editStatusID;
    }

    public function editfaculty($facultyID)
    {
        $this->setup_view('fmis/faculty/editfaculty');
    }

    public function editpermission($facultyID = 14344)
    {
        $data = array(
            'facultyID' => $facultyID
        );
        $this->setup_view('fmis/faculty/editpermission', $data);
    }

    public function uploadphoto()
    {
        $config['upload_path'] = './images/fmis/members/'.$this->session->userdata('user_id');
        $config['allowed_types'] = 'jpg';
        $config['file_name'] = "temp";
        $config['overwrite'] = true;

        if (!file_exists($config['upload_path'])) {
            mkdir($config['upload_path'], 0777, true);
        }

        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        $this->load->library('user_agent');


        if( ! ($this->upload->do_upload('upload_photo'))) {
            $data = array(
                'success' => false,
                'page_title' => 'Error',
                'message' => $this->upload->display_errors(),
                'referrer' => $this->agent->referrer()
            );
        }
        else {
            $data = array(
                'success' => true,
                'page_title' => 'Success',
                'user_id' => $this->session->userdata('user_id'),
                'username' => $this->session->userdata('username'),
                'message' => 'Your file has been successfully uploaded',
                'referrer' => $this->agent->referrer()
            );
        }


        echo json_encode($data);

    }

}
